using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace ElteIk.RoboSoccer.WinFormsGui
{
    /// <summary>
    /// A tool from timing UI actions.
    /// </summary>
    public class StopWatch : IDisposable
    {
        private Timer timer;

        private double seconds;
        private DateTime endTime;
        private int tickInterval;

        public StopWatch(double seconds, int tickInterval, bool autoStart)
        {
            this.timer = new Timer();
            
            this.seconds = seconds;
            this.tickInterval = tickInterval;
            
            this.timer.Interval = tickInterval;
            this.timer.Tick += new EventHandler(timer_Tick);
            
            if (autoStart)
                Start();
        }

        void timer_Tick(object sender, EventArgs e)
        {
            if (DateTime.Now >= endTime)
            {
                TimeOut();
            }
            OnTick(endTime.Subtract(DateTime.Now).TotalSeconds);
        }

        private void TimeOut()
        {
            timer.Stop();
            OnStopped();
        }

        public StopWatch(double seconds)
            : this(seconds, 100, false)
        {
        }

        public void Start()
        {
            endTime = DateTime.Now.AddSeconds(seconds);
            timer.Start();
        }

        public class TickEventArgs : EventArgs
        {
            private double remainingTime;
            public double RemainingTime { get { return remainingTime; } }
            public TickEventArgs(double remainingTime)
            {
                this.remainingTime = remainingTime;
            }
        }

        public event EventHandler<TickEventArgs> Tick;

        protected virtual void OnTick(double remainingTime)
        {
            if (Tick != null)
                Tick(this, new TickEventArgs(remainingTime));
        }

        public event EventHandler Stopped;
        protected virtual void OnStopped()
        {
            if (Stopped != null)
                Stopped(this, EventArgs.Empty);
        }


        #region IDisposable Members

        public void Dispose()
        {
            timer.Dispose();
        }

        #endregion

        public void Stop()
        {
            timer.Stop();
        }
    }
}
